/*
 * @Author: RYPY
 * @Date: 2021-02-20 17:48:22
 * @LastEditors: RYPY
 * @LastEditTime: 2021-03-21 14:14:41
 */

var express = require('express');
var path = require('path');
var logger = require('morgan');
const {Msg,checkToken}=require("./until/config");
const Session=require("express-session");
const cors=require("cors");

var app = express();

//开启会话模式功能
app.use(Session({
  secret:"course-sessionID",
  resave:false,
  saveUninitialized:true,
  cookie:{
    maxAge:1*60*60*1000
  }
}));

//开启跨域访问功能
app.use(cors({
  origin:true,
  methods:["Post","GET"],
  credentials:true
}));

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(express.static(path.join(__dirname, 'public')));

//引入子路由，绑定主路由，
// app.use('/', indexRouter);
//不需要拦截的路由
app.use('/api', require("./routes/mainRouter"));
app.use('/api', require("./routes/loginRouter"));
app.use("/api",require("./routes/courseRouter"));
app.use("/api",require("./routes/listRouter"));

//拦截器
app.use("/*",(req,res,next)=>{
  //通过登录token值，判定是否拦截
  let tokenData=req.headers.authorization?req.headers.authorization:"";
  if(!(tokenData)){
    res.send(Msg(201,"请先登录"));
  }else if(!checkToken(tokenData)){
      res.send(Msg(201,"无效token"));
  }else{
    next();
  }
});
//需要拦截的路由
app.use("/api",require("./routes/userRouter"));
app.use("/api",require("./routes/usercourseRouter"));


// 开启资源路由提示
app.use((req, res, next)=> {
  res.send(Msg(404,"您所访问的资源不存在！"));
});

// 开启服务器端运行时错误提示
app.use((err, req, res, next)=> {
  res.send(Msg(500,`${err.message}`));
});

module.exports = app;
